package com.kylin.common.weixin.miniapp;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.kylin.common.core.util.HttpUtils;
import com.kylin.common.weixin.util.WxRequest;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 腾讯云服务
 * @author wuhao
 * @version 1.0 - 2023/3/22
 */
public class TcbService {

    /** 上传文件接口 */
    private static final String UPLOAD_FILE_URL = "/tcb/uploadfile";
    /** 下载文件接口 */
    private static final String DOWNLOAD_FILE_URL = "/tcb/batchdownloadfile";

    /**
     * 获取文件上传链接
     * @param accessToken 接口调用凭证
     * @param env 云环境ID
     * @param path 上传路径
     * eg.{
     *   "env": "werun—id",
     *   "path": "web/test.zip"
     * }
     * @version 1.0  by wuhao at 2019-03-04
     */
    public static JSONObject getUploadFileUrl(String accessToken, String env, String path){
        String url = UPLOAD_FILE_URL;
        if(StringUtils.hasText(accessToken)) {
            url += "?access_token=" + accessToken;
        }
        JSONObject params = new JSONObject();
        params.put("env", env);
        params.put("path", path);
        return WxRequest.post(url,params.toJSONString());
    }

    /**
     * 上传文件
     * @param cosFileParams 获取文件上传链接返回参数
     * @param filePath 文件路径名称
     * @param file 二进制文件
     * @return
     * @author wuhao
     * @version 1.0.0 - 2023/3/25
     */
    public static String uploadFile(JSONObject cosFileParams, String filePath, File file) {
        String url = cosFileParams.getString("url");
        Map<String, String> data = new HashMap<>();
        data.put("key", filePath);
        data.put("Signature", cosFileParams.getString("authorization"));
        data.put("x-cos-security-token", cosFileParams.getString("token"));
        data.put("x-cos-meta-fileid", cosFileParams.getString("cos_file_id"));
        String resultStr = HttpUtils.upload(url, file, data);
        return resultStr;
    }


    /**
     * 批量下载文件
     * @param accessToken 接口调用凭证
     * @param env 云环境ID
     * @param fileList 文件列表
     * eg.{
     *   "env": "test2-4a89da",
     *   "file_list": [
     *     {
     *       "fileid":"cloud://test2-4a89da.7465-test2-4a89da/A.png",
     *       "max_age":7200
     *     }
     *   ]
     * }
     * @version 1.0  by wuhao at 2019-03-04
     */
    public static JSONObject batchDownloadFile(String accessToken, String env, JSONArray fileList){
        String url = DOWNLOAD_FILE_URL;
        if(StringUtils.hasText(accessToken)) {
            url += "?access_token=" + accessToken;
        }
        JSONObject params = new JSONObject();
        params.put("env", env);
        params.put("file_list",fileList);
        return WxRequest.post(url,params.toJSONString());
    }

}
